<template>
  <div class="bground">
    <el-divider content-position="left" style="font-size: 100px"><p style="font-size: 20px">用户地址簿</p></el-divider>
    <div class="container">
      <div class="table-container">
        <!-- 表格代码 -->
        <el-form ref="userAddressFormRef" :model="userAddress" label-width="120px" :rules="rules" :data="tableData">
          <el-form-item label="联系人" prop="consignee">
            <el-input v-model="userAddress.consignee" placeholder="请填写收货人姓名" />
          </el-form-item>

          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="userAddress.sex">
              <el-radio label="MALE" >男</el-radio>
              <el-radio label="FEMALE" >女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userAddress.phone" placeholder="请填写收货手机号码" />
          </el-form-item>


          <el-form-item label="收货地址" >
            <el-select v-model="provinceCode"  placeholder="请选择所在省份" @change="provinceChange(provinceCode)">
              <el-option v-for="item in province" :key="item.areaId" :label="item.areaName" :value="item.areaId"  />
            </el-select>
            <el-select v-model="cityCode" placeholder="请选择所在城市" @change="cityChange(cityCode)">
              <el-option :key="0" :value="0" label="请选择所在城市"/>
              <el-option v-for="item in city" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
            </el-select>
            <el-select v-model="districtCode" placeholder="请选择所在区域" @change="districtChange(districtCode)">
              <el-option :key="0" :value="0" label="请选择所在区域"/>
              <el-option v-for="item in district" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
            </el-select>
            <el-input v-model="userAddress.detail" prop="detail" placeholder="请填写详细地址" />
          </el-form-item>

          <el-form-item label="设为默认地址">
            <el-radio-group v-model="userAddress.isDefault">
              <el-radio  label="1" >是</el-radio>
              <el-radio  label="0" >否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="btnCommit">确认</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="map-container">
        <!-- 地图代码 -->
        <div>
          <MapContainer :locations="locations"></MapContainer>
        </div>
      </div>
    </div>

    <div>
      <el-divider content-position="left">地址列表</el-divider>
      <el-table :data="tableData" style="width: 100%" max-height="450">

        <el-table-column fixed prop="consignee" label="联系人" style="width: 5%" />
        <el-table-column fixed prop="sex" label="性别" style="width: 20%" >
          <template v-if="tableData.sex === '1'">
            男
          </template>
          <template v-else>
            女
          </template>
        </el-table-column>
        <el-table-column fixed prop="phone" label="电话" style="width: 5%" />
        <el-table-column fixed prop="provinceName" label="省名称" style="width: 5%" />
        <el-table-column fixed prop="cityName" label="城名称" style="width: 20%" />
        <el-table-column fixed prop="districtName" label="区名称" style="width: 20%" />
        <el-table-column fixed prop="detail" label="详细地址" style="width: 40%" />
        <el-table-column fixed prop="isDefault" label="是否为默认地址" style="width: 5%" >
          <template v-if="tableData.isDefault === '1'">
            是
          </template>
          <template v-else>
            否
          </template>
        </el-table-column>
        <el-table-column fixed label="Delete" style="width: 10%">
          <template #default="scope">
            <el-button
                    link
                    type="primary"
                    size="small"
                    @click.prevent="deleteRow(scope.row.id,scope.$index)"
            >
              Remove
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

  </div>




</template>

<script setup>
    import {reactive,onMounted, ref, computed} from 'vue'
    import {findAddress} from "@/api/user";
    import { useStore } from "vuex";
    import {
      getCity,
      getCityName,
      getDistrict,
      getDistrictName,
      getProvince,
      getProvinceName,
      submitAddress,
      deleteAddress
    } from "@/api/addressSelect";
    import MapContainer from '@/components/MapContainer.vue'
    import {$get} from "../../utils/addressRequest";

    const store = useStore();

    const tableData = ref([]); // table数据
    onMounted(() => {
      const id=ref(store.getters.getId)
      findAddress({id:id.value}).then((res)=>{
        // for(let i=0;i<res.data.length;i++){
        //     tableData.value.push(res.data[i])
        //     console.log(users.value[i])
        // }
        tableData.value=res.data
        console.log(tableData.value)
      })
      getProvince().then(res => {
        // province.value=res.data
        for(let i=0;i<res.data.length;i++){
            province.value.push(res.data[i])
        }
      })
    })


    const userAddress = ref({
      userId: '',
      consignee: '',
      sex: '',
      phone: '',
      provinceName: '',
      cityName: '',
      districtName: '',
      detail: '',
      isDefault: '0',
      provinceCode:'',
      cityCode:'',
      districtCode:'',
    })

    const provinceCode=ref();

    const province=ref([]);

    const cityCode=ref();

    const city=ref([]);

    const districtCode=ref();

    const district=ref([])
    //调用api的地址，拼接省市区的名称
    const nowProvinceName=ref('')
    const nowCityName=ref('')
    const nowDistrictName=ref('')
    const nowAddress=ref('')
    const locations=ref([])

    const rules=reactive({
      consignee: [
        /*
        * 是否必须输入，不输入提示的消息，
        * 最小长度，最大长度
        * */
        { required: true, message: '请输入收货人', trigger: 'blur' },
        { min: 2, max: 10, message: '收货人姓名长度为2-10', trigger: 'blur' },
      ],
      sex: [
        { required: true,message:'请选择性别',trigger:'blur'}
      ],
      phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { min:11,max:11, message: '请输入正确的手机号', trigger: 'blur' },
      ],
      detail: [
        { required: true, message: '地址不能为空', trigger: 'blur' }
      ]

    });





    const userId = computed(() => {
      return store.getters.getId
    })

    const provinceChange= async (id)=>{
      city.value=[]
      district.value=[]
      getCity({id:id}).then(res=>{
        for(let i=0;i<res.data.length;i++){
          city.value.push(res.data[i])
        }
      })
      //获取id对应名称
      nowProvinceName.value=province.value.find(c=>c.areaId==id).areaName
      nowAddress.value=nowProvinceName.value
      userAddress.value.provinceName=nowProvinceName.value
      userAddress.value.provinceCode=id
      cityCode.value=0
      districtCode.value=0
      await toMap(nowAddress.value)
    }


    const cityChange=async (id)=>{
      if(id==0){
        return
      }
      district.value=[]
      getDistrict({id:id}).then(res =>{
        for(let i=0;i<res.data.length;i++){
          district.value.push(res.data[i])
        }
      })
      nowCityName.value=city.value.find(c=>c.areaId==id).areaName
      nowAddress.value=nowProvinceName.value+nowCityName.value
      userAddress.value.cityName=nowCityName.value
      userAddress.value.cityCode=id
      districtCode.value=0
      await toMap(nowAddress.value)
    }

    const districtChange=async (id)=>{
      if(id==0){
        return
      }
      nowDistrictName.value=district.value.find(c=>c.areaId==id).areaName
      nowAddress.value=nowProvinceName.value+nowCityName.value+nowDistrictName.value
      userAddress.value.districtName=nowDistrictName.value
      userAddress.value.districtCode=id
      await toMap(nowAddress.value)
    }


    //转换为经纬度，并传给子组件
    const toMap=async (Address)=>{
      let {geocodes} = await $get('https://restapi.amap.com/v3/geocode/geo?parameters',{
        //Web端的key
        key:'2b71974950a51f8c24eb45a1e462a84e',
        //地址
        address:Address
      })
      //坐标地址
      let {location}=geocodes[0]
      //传给子组件的值
      locations.value=location
    }

    const btnCommit=()=>{
      userAddress.value.userId=store.getters.getId
      console.log(userAddress.value)
      submitAddress(userAddress.value)
      tableData.value.push(userAddress.value)
      location.reload();
    }

    const deleteRow=(orderId,index)=>{
      deleteAddress({id:orderId}).then((res)=>{
        tableData.value.splice(index,1)
      })
    }

</script>

<style scoped>
  .bground{
    width: 100%;
    background-color:rgba(0, 191, 255, 0.2);
    border: 1px solid #ccc;
    border-radius: 10px;
    /*background-image: url('../../views/slider-pic/bizhi4.png');*/
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
  }
  .container {
    display: flex;
    height: 350px;
  }

  .table-container {
    width: 70%;
    height:40%;
  }

  .map-container {
    width: 30%;
    height:50%;
  }

</style>